package com.gd.iot.energy.config.shiro;


import cn.hutool.core.util.StrUtil;
import com.gd.iot.energy.consts.SystemConsts;
import com.gd.iot.energy.pojo.superadmin.dto.AdminDTO;
import com.gd.iot.energy.pojo.superadmin.dto.PermissionDTO;
import com.gd.iot.energy.pojo.superadmin.dto.RoleDTO;
import com.gd.iot.energy.service.common.LoginService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

/**
 * Description
 *
 * @author kris
 * @date Created at 2020/8/4 9:53
 */

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private LoginService loginService;

    @Value("${energy.login.lockTimeInMills:86400000}")
    private Long lockTimeInMills;

    @Value("${energy.superadmin.name:超级管理员}")
    private String superAdminName;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录用户名
        AdminDTO adminDTO = (AdminDTO) principalCollection.getPrimaryPrincipal();

        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (RoleDTO role : adminDTO.getRoles()) {
            //添加角色
            simpleAuthorizationInfo.addRole(role.getName());
            //添加权限
            for (PermissionDTO permissionDTO : role.getPermissionDTOS()) {
                simpleAuthorizationInfo.addStringPermission(permissionDTO.getPerms());
            }
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //加这一步的目的是在Post请求的时候会先进认证，然后在到请求
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            throw new UnknownAccountException();
        }
        //获取用户信息
        AdminDTO user = loginService.getAdminByName(username);

        if (user == null) {
            throw new UnknownAccountException();
        }
        if (SystemConsts.BooleanEnum.FALSE.value.equals(user.getIsEnabled())) {
            throw new DisabledAccountException();
        }
//        if (SystemConsts.BooleanEnum.TRUE.value.equals(user.getIsLocked())) {
//            if (user.getLockedDate().getTime() + lockTimeInMills < System.currentTimeMillis()) {
//                loginService.unlock(user);
//            }else {
//                throw new LockedAccountException();
//            }
//        }

        loginService.updateLoginInfo(user);

        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

    @Override
    public boolean isPermitted(PrincipalCollection principals, String permission){
        return isSuperAdmin(principals) || super.isPermitted(principals,permission);
    }
    @Override
    public boolean hasRole(PrincipalCollection principals, String roleIdentifier) {

        return isSuperAdmin(principals) || super.hasRole(principals,roleIdentifier);
    }

    /**
     * 是否是超级管理员
     * @param principals
     * @return
     */
    private boolean isSuperAdmin(PrincipalCollection principals) {
        AdminDTO user = (AdminDTO) principals.getPrimaryPrincipal();
        if (user.getRoles() != null) {
            for (RoleDTO role : user.getRoles()) {
                if (superAdminName.equals(role.getName())) {
                    return true;
                }
            }
        }
        return false;
    }
}

